package com.baseandroid.jpush;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import com.androidbase.utils.DeviceUuid;
import com.androidbase.utils.DigestUtils;
import com.androidbase.utils.NetUtils;
import com.baseandroid.config.Api;
import com.baseandroid.config.Global;
import com.qianbao.qianbaobusiness.BuildConfig;

import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import timber.log.Timber;

public class JPushBizutils {
    private static final int MSG_SET_ALIAS_AND_TAGS = 0x1001;

    private static HandlerThread mHandlerThread;
    private static Handler mHandler;

    public static void initJPush() {
        JPushInterface.init(Global.getContext());
        if (BuildConfig.DEBUG) {
            JPushInterface.setDebugMode(true);
        }

        try {
            Timber.e("Push Alias = " + Global.getsJpushAlias());
            if (Global.getUserInfoBean().getUser() != null && !Global.getsJpushAlias()
                    .equals(DigestUtils.md5Hex(Global.getUserInfoBean()
                            .getUser()
                            .getMobile() + DeviceUuid.getDeviceId(Global.getContext())))) {
                JPushInterface.stopPush(Global.getContext());
                mHandlerThread = new HandlerThread(JPushBizutils.class.getName());
                mHandlerThread.start();

                mHandler = new Handler(mHandlerThread.getLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case MSG_SET_ALIAS_AND_TAGS:
                                resumeJPush((String) msg.obj);
                                Set<String> tagset = new HashSet<>();
                                if (Api.isDevelop) {
                                    tagset.add("Develop");
                                } else {
                                    tagset.add("Product");
                                }
                                JPushInterface.setAliasAndTags(Global.getContext(), (String) msg.obj, tagset, mAliasCallback);

                                break;

                            default:
                                break;
                        }
                    }
                };

                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS_AND_TAGS, DigestUtils
                        .md5Hex(Global.getUserInfoBean()
                                .getUser()
                                .getMobile() + DeviceUuid.getDeviceId(Global.getContext()))), 2000);

            } else {
                if (JPushInterface.isPushStopped(Global.getContext())) {
                    JPushInterface.resumePush(Global.getContext());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void resumeJPush(String newAlias) {
        Global.setsJpushAlias(newAlias);
        JPushInterface.resumePush(Global.getContext());
    }

    public static void stopJPush(String newAlias) {
        Global.setsJpushAlias(newAlias);
        JPushInterface.stopPush(Global.getContext());
    }

    private static TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    if (mHandler != null && mHandlerThread.getLooper() != null) {
                        mHandler.removeCallbacks(null);

                        mHandlerThread.getLooper().quit();
                    }
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    if (NetUtils.isConnected()) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS_AND_TAGS, alias), 1000 * 60);
                    } else {
                        logs = "No network";
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
            }

            Log.d("JPush", "logs = " + logs);
        }

    };
}
